package com.tf_cut.backend.request.xml;


import org.xml.sax.InputSource;

import com.tf_cut.backend.request.MybankApiException;
import com.tf_cut.backend.request.Request;
import com.tf_cut.backend.request.RequestBody;
import com.tf_cut.backend.request.RequestDocument;
import com.tf_cut.backend.request.Requests;
import com.tf_cut.backend.request.util.JaxbUtil;
import com.tf_cut.backend.seller.enums.MybankApiExceptionEnum;
import com.tf_cut.backend.util.MybankConstants;
import com.tf_cut.backend.util.RequestHead;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 * Encapsulating XML common operations
 */
public final class XmlUtils {

    public static String requestXmlBuild(RequestHead requestHead, RequestBody requestBody) throws MybankApiException {
        if (null == requestHead || null == requestBody) {
            throw new MybankApiException(MybankApiExceptionEnum.BUILD_XML_EXCEPTION);
        }
        return JaxbUtil.convertToXml(new RequestDocument(new Requests(requestHead, requestBody)), MybankConstants.CHARSET_UTF8);
    }

    /**
     * XML报文格式检查
     *
     * @param xmlContent
     * @return true/false
     */
    public static boolean isXmlDocument(String xmlContent) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlContent)));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
